package cn.thornbird.orgsync.controller;

import cn.thornbird.orgsync.annotation.CurrentUser;
import cn.thornbird.orgsync.entity.City;
import cn.thornbird.orgsync.exception.BadRequestException;
import cn.thornbird.orgsync.exception.ForbiddenException;
import cn.thornbird.orgsync.exception.NotFoundException;
import cn.thornbird.orgsync.model.PageList;
import cn.thornbird.orgsync.model.Result;
import cn.thornbird.orgsync.model.UserData;
import cn.thornbird.orgsync.model.combined.CityObject;
import cn.thornbird.orgsync.service.CityService;
import cn.thornbird.orgsync.vo.record.CityRecord;
import cn.thornbird.orgsync.vo.request.CityQueryRequest;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping(value = "/api/city")
@Api
@AllArgsConstructor
public class CityController {

    private final CityService cityService;

    @GetMapping("find/{id}")
    public Result<CityObject> find(@PathVariable String id) throws NotFoundException {
        return Result.success(cityService.find(id));
    }

    @GetMapping("findAll")
    public Result<List<CityObject>> find() {
        return Result.success(cityService.findAll());
    }

    @GetMapping("query/{parentId}")
    public Result<List<City>> findCities(@PathVariable String parentId) {
        parentId = parentId.equals("null") ? null : parentId;
        return Result.success(cityService.findCities(parentId));
    }

    @GetMapping("query")
    public Result<PageList<CityObject>> query(CityQueryRequest cityQueryRequest, Integer pageNumber, Integer pageSize) {
        return Result.success(cityService.query(cityQueryRequest, pageNumber, pageSize));
    }

    @PostMapping("save")
    public Result<CityObject> save(@CurrentUser @ApiIgnore UserData userData, @RequestBody @Valid CityRecord cityRecord)
            throws BadRequestException, NotFoundException, ForbiddenException {
        userData.checkAuthority(UserData.ADMIN);
        return Result.success(cityService.save(cityRecord));
    }

    @DeleteMapping("delete/{id}")
    public Result<CityObject> delete(@CurrentUser @ApiIgnore UserData userData, @PathVariable String id)
            throws BadRequestException, NotFoundException, ForbiddenException {
        userData.checkAuthority(UserData.ADMIN);
        return Result.success(cityService.delete(id));
    }

}
